<template>
    <el-container>
        <el-main>
            <el-row :gutter="10">
                <el-col :span="6">
                    <el-card class="box-card">
                        <div slot="header">
                            <span>角色查询</span>
                        </div>
                        <el-form
                                ref="roleQueryForm"
                                :model="roleQueryForm"
                                label-width="80px"
                                :inline="true"
                                label-position="right"
                                size="mini">
                            <el-form-item label="角色名称" prop="roleName">
                                <el-input v-model="roleQueryForm.roleName" autocomplete="off" ></el-input>
                            </el-form-item>
                            <el-form-item label="角色描述" prop="roleDesc">
                                <el-input v-model="roleQueryForm.roleDesc" autocomplete="off" ></el-input>
                            </el-form-item>
                            <el-form-item style="float: right">
                                <el-button type="primary" @click="queryRoleByCondiction">查询</el-button>
                                <el-button type="primary" @click="resetQueryRoleForm">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>

                    <el-card class="box-card">
                        <div slot="header">
                            <span>查询结果</span>
                        </div>
                        <el-table
                                :data="roleData"
                                stripe
                                style="width: 100%"
                                height="350"
                                highlight-current-row
                                @row-click="onRowClick"
                        >
                            <el-table-column
                                    prop="roleName"
                                    label="角色名称"
                                    width="100">
                            </el-table-column>
                            <el-table-column
                                    prop="roleDesc"
                                    label="角色描述"
                                    width="180">
                                <template slot-scope="scope">
                                    <el-popover trigger="hover" placement="top">
                                        <p>{{ scope.row.roleDesc}}</p>
                                        <div slot="reference" class="name-wrapper">
                                            <el-tag size="medium">{{ scope.row.roleDesc}}</el-tag>
                                        </div>
                                    </el-popover>
                                </template>
                            </el-table-column>
                        </el-table>
                        <!--分页插件-->
                        <div>
                            <el-pagination
                                    background
                                    layout="prev, pager, next"
                                    :total="rolePage.total"
                                    :page-size="rolePage.size"
                                    :current-page.sync="rolePage.current"
                                    @current-change="queryRole"
                            />
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="18">
                    <el-card class="box-card">
                        <div slot="header">
                            <span>角色管理</span>
                        </div>
                        <el-form
                                ref="roleEditForm"
                                :model="roleEditForm"
                                :rules="rules"
                                label-width="80px"
                                label-position="right"
                                size="mini"
                                style="width: 600px"
                        >
                            <el-form-item label="id" prop="id" v-show="false">
                                <el-input v-model="roleEditForm.id" autocomplete="off" ></el-input>
                            </el-form-item>
                            <el-form-item label="sort" prop="sort" v-show="false">
                                <el-input v-model="roleEditForm.sort" autocomplete="off" ></el-input>
                            </el-form-item>
                            <el-form-item label="角色名称" prop="roleName">
                                <el-input v-model="roleEditForm.roleName" autocomplete="off" ></el-input>
                            </el-form-item>
                            <el-form-item label="角色描述" prop="roleDesc">
                                <el-input v-model="roleEditForm.roleDesc" autocomplete="off" ></el-input>
                            </el-form-item>
                            <el-form-item label="角色代码" prop="roleCode">
                                <el-input v-model="roleEditForm.roleCode" autocomplete="off" :disabled="!roleAdd"></el-input>
                            </el-form-item>
                            <el-form-item label="角色是否可用" prop="status" v-show="!roleAdd" :rules="!roleAdd?rules.status:[{retuired:false}]">
                                <dict-select
                                        code-name="status"
                                        :dict-value.sync="roleEditForm.status"
                                        :disabled="roleAdd"
                                />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="saveRole">保存角色</el-button>
                                <el-button type="primary" @click="addNewRole">新增角色</el-button>
                                <el-button type="danger" @click="deleteRole" :disabled="roleAdd">删除角色</el-button>
                            </el-form-item>
                        </el-form>
                    </el-card>
                    <el-card class="box-card">
                        <div slot="header">
                            <span>权限明细</span>
                            <el-button-group style="float: right">
                                <el-button type="primary" size="mini" @click="saveRoleAuthority">保存权限</el-button>
                            </el-button-group>
                        </div>

                        <el-tree
                                ref="menuTree"
                                :data="menuData"
                                :props="defaultProps"
                                :default-expanded-keys="expandMenu"
                                node-key="id"
                                show-checkbox
                        >
                        </el-tree>
                    </el-card>
                    </el-col>
            </el-row>
        </el-main>
    </el-container>
</template>

<script>
    import {defaultQueryPage,defaultResultPage} from "@/lib/QueryPageUtil";
    import {listRole,addRole,deleteRole,updateRole,getRole} from "@/api/role";
    import {getMenuIdsByRoleId,updateMenuForRole} from '@/api/roleMenu'
    import DictSelect from "@/components/SysDictSelect";
    import {getMenuTree} from "@/api/menu";
    import {refresh} from "@/api/system";

    export default {
    name: "RoleManager",
        components: {DictSelect},
        data(){
        return{
            //角色查询表单
            roleQueryForm:{
                roleName:"",
                roleDesc:""
            },
            //角色列表
            roleData:[],
            roleAdd:true,
            //角色编辑表单
            roleEditForm:{
                id:null,
                roleName:null,
                roleDesc:null,
                roleCode:null,
                status:null,
                sort:null,
            },
            rules:{
                roleName:[
                    {required:true,message:"不能为空",trigger:'blur'}
                ],
                roleCode:[
                    {required:true,message:"不能为空",trigger:'blur'}
                ],
                status:[
                    {required:true,message:"不能为空",trigger:'change'}
                ],
            },
            rolePage:defaultQueryPage(),
            //菜单树展开数据
            expandMenu:['0'],
            //菜单树数据
            menuData:[],
            //菜单树定义
            defaultProps:{
                children:"children",
                label:'menuName',
                isLeaf:'isLeaf',
                disabled:this.treeDisabled
            },
        }
    },
    mounted(){
        this.queryRole()
    },
    methods:{
        //按条件查询角色
        queryRoleByCondiction(){
            this.rolePage = defaultQueryPage(this.roleQueryForm)
            this.queryRole()
        },
        //查询角色信息
        queryRole(){
            listRole(this.rolePage)
                .then(res => {
                    this.roleData = [...res.data.records]
                    defaultResultPage(res.data,this.rolePage);
                }).catch(err => {
                    this.$message.error(err.message)
            })
        },
        //重置查询角色信息
        resetQueryRoleForm(){
            this.$refs.roleQueryForm.resetFields()
        },
        //新增角色清空表单信息
        addNewRole(){
            //更新标识roleAdd标识
            this.roleAdd = true
            //清空表单信息
            this.$refs.roleEditForm.resetFields();
            console.log(this.roleEditForm)
        },
        //保存角色信息
        saveRole(){
            this.$refs.roleEditForm.validate((valid) =>{
                if(valid){
                    if(this.roleAdd){
                        addRole(this.roleEditForm)
                            .then(res => {
                                this.$message.success("保存成功！")
                                //更新标识roleAdd标识
                                this.roleAdd = false
                                //重新查询左侧结果
                                this.queryRole()
                                this.roleEditForm = {...res.data}
                            }).catch(err => {
                            this.$message.error(err.message)
                        })
                    }else{
                        updateRole(this.roleEditForm)
                            .then(res => {
                                this.$message.success("保存成功！")
                            }).catch(err => {
                            this.$message.error(err.message)
                        })
                    }
                }
            })

        },
        //删除角色
        deleteRole(){
            this.$confirm("是否确认删除【"+this.roleEditForm.roleName+"】？")
                .then( _ =>{
                    let data = {roleId:this.roleEditForm.id}
                    deleteRole(data)
                        .then(res =>{
                            this.$message.success("已删除【"+this.roleEditForm.roleName+"】")
                            //删除后，清理表单信息，并且重新查询角色信息
                            this.addNewRole()
                            //重新查询角色信息
                            this.queryRole()
                        }).catch(err => {
                            this.$message.error(err.message)
                    })

                }).catch(_ =>{
                    this.$message.info("你不删除【"+this.roleEditForm.roleName+"】咯")
            })
        },
        //角色被选中触发事件
        onRowClick(currentRow){
            //加载角色信息
            let data = {roleId:currentRow.id}
            getRole(data)
                .then(res =>{
                    this.roleEditForm = {...res.data}
                    this.roleAdd = false
                    this.queryMenuTree();

                }).catch(err => {
                    console.log(err)
            })
        },
        queryMenuTree(){
            getMenuTree()
                .then(res => {
                    //恢复默认展开节点
                    this.expandMenu = ['0']
                    this.menuData = res.data
                    this.getMenuIdsByRoleId(this.roleEditForm.id)
                })
                .catch(err =>{
                    this.$message.error(err.message)
                })
        },
        //根据角色获取当前角色已有的菜单权限信息
        getMenuIdsByRoleId(roleId){
            let data = {roleId:roleId}
            getMenuIdsByRoleId(data)
                .then(res => {
                    this.expandMenu = res.data
                    /*遍历后端返回的菜单信息，解决使用setCheckedKeys选中了父节点时所有子菜单被选中的情况：
                    1.后端数据的返回格式为List<String>
                    2.从当前的菜单树中获取对应Id节点，判断是否为叶子节点，然后进行选中*/
                    res.data.forEach(menuId =>{
                        let node = this.$refs.menuTree.getNode(menuId);
                        if(node.isLeaf){
                            this.$refs.menuTree.setChecked(node,true)
                        }
                    })
                }).catch(err => {
                   this.$message.error(err.message)
            })
        },
        //保存用户选中的权限
        saveRoleAuthority(){
            //获取所有从叶子节点到根节点的集合
            let checkNodes = this.$refs.menuTree.getCheckedNodes(false,true)
            //遍历转换获取ID集合
            let menuIds =  checkNodes.map((node) =>{
                return node.id
            })
            //组装后台需要的数据
            let roleMenuData = {roleId:this.roleEditForm.id,menuIds:menuIds}
            updateMenuForRole(roleMenuData)
                .then(res => {
                    this.$message.success("【"+this.roleEditForm.roleName+"】权限保存成功！")
                }).catch(err => {
                    this.$message.error(err.message)
            })
        },
        //设置权限菜单树的是否可用
        treeDisabled(data,noed){
            //后端返回的菜单的为是否可用，true为可用，false为不可用，element ui要求的是disable，所以取反即可
            return !data.status
        }
    }
}
</script>

<style scoped>

</style>